package cn.tedu.weibo.controller;

import cn.tedu.weibo.mapper.UserMapper;
import cn.tedu.weibo.pojo.dto.UserDTO;
import cn.tedu.weibo.pojo.dto.UserLoginDTO;
import cn.tedu.weibo.pojo.entity.User;
import cn.tedu.weibo.pojo.vo.UserVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Date;

@RestController
@RequestMapping("/v1/users")
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @PostMapping("/reg")
    public int addUser(@RequestBody UserDTO userDto){
        User user=new User();
        if(userMapper.findByUsername(userDto.getUsername())!=null){
            return 2;
        }else {
        BeanUtils.copyProperties(userDto,user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;
        }
    }
    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDto, HttpSession session){
        User user=userMapper.findByUsername(userLoginDto.getUsername());
        if(user!=null){
            if(userLoginDto.getPassword().equals(user.getPassword())){
                //登陆成功后将当前用户存入session对象
                session.setAttribute("user",user);
                return 1;
            }
            else {
                return 2;
            }
        }else {
            return 3;
        }
    }
    @GetMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
        User user=(User)session.getAttribute("user");
        System.out.println(user);
        if (user==null){
            return null;
        }else {
            UserVO userVO = new UserVO();
            BeanUtils.copyProperties(user, userVO);
            return userVO;
        }
    }
    @GetMapping("/logout")
    public void logout(HttpSession session){
        session.removeAttribute("user");
    }
}
